import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: uni.getStorageSync('token') || '',
    userInfo: uni.getStorageSync('userInfo') || null,
    isLogin: !!uni.getStorageSync('token')
  }),
  
  getters: {
    getUserInfo: (state) => state.userInfo,
    getToken: (state) => state.token,
    getLoginStatus: (state) => state.isLogin
  },
  
  actions: {
    setToken(token) {
      this.token = token
      this.isLogin = true
      uni.setStorageSync('token', token)
    },
    
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      uni.setStorageSync('userInfo', userInfo)
    },
    
    async login(username, password) {
      try {
        // 这里调用登录API
        const res = await uni.request({
          url: '/api/login',
          method: 'POST',
          data: {
            username,
            password
          }
        })
        
        if (res.data.code === 0) {
          this.setToken(res.data.data.token)
          this.setUserInfo(res.data.data.userInfo)
          return true
        }
        return false
      } catch (error) {
        console.error('Login failed:', error)
        return false
      }
    },
    
    async register(data) {
      try {
        const res = await uni.request({
          url: '/api/register',
          method: 'POST',
          data
        })
        
        if (res.data.code === 0) {
          this.setToken(res.data.data.token)
          this.setUserInfo(res.data.data.userInfo)
          return true
        }
        return false
      } catch (error) {
        console.error('Register failed:', error)
        return false
      }
    },
    
    logout() {
      this.token = ''
      this.userInfo = null
      this.isLogin = false
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
      uni.reLaunch({
        url: '/pages/login/login'
      })
    },
    
    async updateUserInfo(data) {
      try {
        const res = await uni.request({
          url: '/api/user/update',
          method: 'POST',
          data
        })
        
        if (res.data.code === 0) {
          this.setUserInfo({
            ...this.userInfo,
            ...data
          })
          return true
        }
        return false
      } catch (error) {
        console.error('Update user info failed:', error)
        return false
      }
    }
  }
}) 